var common_ad_ids = [];

var common_pay_type;

var common_auth_id;

var common_company_id;

var common_code_value;

var common_ad_id;

var common_ad_enable = true;

var common_ad_container = null

var common_ad_first_click = true

/**
 * local 本地开发环境
 * dev 服务器开发环境
 * pro 服务器生产环境
 */
var currentEnv = "dev";
var commonTradeHostName = null;
var commonTradeWebHostName = null;


var common_init_ads = function () {
    common_ad_ids[0] = ("u4313189");//评论区样式_01
    common_ad_ids[1] = ("u4313186");//原生文字链_01
    common_ad_ids[2] = ("u4313183");//源生大图_01
    common_ad_ids[3] = ("u4313181");//源生三图_01
    common_ad_ids[4] = ("u4313180");//源生图文_01
    common_ad_ids[5] = ("u4313179");//源生缩略图_01
    common_ad_ids[6] = ("u4313269");//图文广告_搜索推荐
    common_ad_ids[7] = ("u4313268");//图文广告_悬浮
    common_ad_ids[8] = ("u4313273")//图文广告_嵌入
};

var get_common_host_name = function () {
    if (commonTradeHostName == null) {
        if (currentEnv == "pro") {
            commonTradeHostName = "https://pay.yanlight.com/trade/"
        } else if (currentEnv == "dev") {
            commonTradeHostName = "https://dev.yanlight.com/trade-dev/"
        } else {
            commonTradeHostName = "http://test.yanlight.com/trade/"
        }
    }
    return commonTradeHostName;
}

var get_web_common_host_name = function () {
    if (commonTradeWebHostName == null) {
        if (currentEnv == "pro") {
            commonTradeWebHostName = "https://pay.yanlight.com/trade-web/"
        } else if (currentEnv == "dev") {
            commonTradeWebHostName = "https://pay.yanlight.com/trade-web/"
        } else {
            commonTradeWebHostName = "http://test.yanlight.com/trade-web/"
        }
    }
    return commonTradeWebHostName;
}

var get_common_company_id = function () {
    return common_company_id;
}

/**
 *
 * @param type 1 微信 2 支付宝
 * @param authId 微信/支付宝授权id
 */
var common_init_pay = function (payType, authId, companyId, codeValue) {
    common_init_ads();

    common_ad_enable = true;
    common_ad_first_click = true
    common_ad_id = common_ad_ids[4];
    common_pay_type = payType;
    common_auth_id = authId;
    common_company_id = companyId;
    common_code_value = codeValue
};

var common_window_listener = function () {

    var countDown = setInterval(function () {
        clearInterval(countDown);
        var frames = document.getElementsByTagName("iframe");
        for (var i = 0; i < frames.length; i++) {
            IframeOnClick.track(frames[i], function () {
                common_request_ad_click()
                alert('1 点击广告列表第一条并观看10秒\n2 返回抽奖列表即可进行抽奖活动\n3 如遇问题，请退出抽奖页重新进入')
            });
        }
    }, 1000)
};

// var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null;
// var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
//
// var onVisibilityChange = function () {
//     if (!document[hiddenProperty]) {
//
//     } else {
//         if (common_adIsTracked) {
//             common_request_ad_click()
//             common_adIsTracked = false;
//             if (common_ad_container != null) {
//                 common_ad_container.hasTracked = false;
//             }
//         }
//     }
// }
// document.addEventListener(visibilityChangeEvent, onVisibilityChange);

var IframeOnClick = {
    resolution: 200,
    iFrames: [],
    interval: null,
    Iframe: function () {
        this.element = arguments[0];
        this.cb = arguments[1];
        this.hasTracked = false;
    },
    track: function (element, cb) {
        this.iFrames.push(new this.Iframe(element, cb));
        if (!this.interval) {
            var _this = this;
            this.interval = setInterval(function () {
                _this.checkClick();
            }, this.resolution);
        }
    },
    checkClick: function () {
        if (document.activeElement) {
            var activeElement = document.activeElement;
            for (var i in this.iFrames) {
                if (activeElement === this.iFrames[i].element) {
                    if (this.iFrames[i].hasTracked == false) {
                        common_ad_container = this.iFrames[i]

                        this.iFrames[i].cb.apply(window, []);
                        this.iFrames[i].hasTracked = true;
                    }
                } else {
                    this.iFrames[i].hasTracked = false;
                }
            }
        }
    }
};


/**
 *
 * @param status true 添加监听，false 不添加监听
 */
var common_init_active = function (status) {
    if (status) {
        // var adContainer = document.getElementById("actives");
        common_window_listener()
    }
};

/**
 *
 * @param status true 添加监听，false 不添加监听
 */
var common_init_ad = function (status) {
    var divId = "_" + Math.random().toString(36).slice(2);
    var divContent = '<div style="" id="' + divId + '"></div>';

    document.write(divContent);
    (window.slotbydup = window.slotbydup || []).push({
        id: common_ad_id,
        container: divId
    });

    if (status) {
        common_window_listener()
    }
};

var common_clear_layer = function () {
    layer.closeAll();
}

var common_confirm = function (title, content, yesFun) {
    layer.open({
        type: 1
        , offset: 'auto' //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
        , id: 'layerDemo' + 'auto' //防止重复弹出
        , content: '<div style="padding: 20px 100px;font-size: 16px;">' + content + '</div>'
        , btn: '我知道了'
        , btnAlign: 'c' //按钮居中
        , shade: 0 //不显示遮罩
        , title: title
        , yes: yesFun
    });
}

var common_toast = function (txt) {
    layer.msg(txt);
};

var common_loading_view;

var common_show_loading = function () {
    common_loading_view = layer.load(2, {
        shade: [0.2, '#000'] //0.1透明度的白色背景
    });
};

var common_dismiss_loading = function closeLoading() {
    if (common_loading_view) {
        layer.close(common_loading_view)
        common_loading_view = null
    }
};


var common_request_ad_click = function () {
    $.ajax({
        url: get_common_host_name() + 'ad/clickCount',
        type: 'POST',
        data: {
            'type': common_pay_type,
            'authId': common_auth_id,
            'adId': common_ad_id,
            'companyId': common_company_id,
            'codeValue': common_code_value
        },
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        dataType: "json",
        success: function (result) {
            if (common_ad_enable) {
                var code = result.errorCode;
                // if (code == 0) {
                //     common_toast("任务已完成~")
                // } else {
                //     var errorMessage = result.errorMsg;
                //     common_toast(errorMessage)
                // }
                console.log("成功")
            } else {
                console.log("不提示消息")
            }
        },
        error: function (error) {
            if (common_ad_enable) {
                console.log("广告点击响应失败")
            } else {
                console.log("广告点击响应失败")
            }
        }
    });
};


var common_banner_click = function () {
    common_toast("哈哈")
}

/**
 *
 * @param type 1 微信 2 支付宝
 * @param authId 微信/支付宝授权id
 */
var common_mask_click = function () {
    window.location.href = get_common_host_name() + 'ad/wheelView?authId=' + common_auth_id + "&type=" + common_pay_type + "&codeValue=" + common_code_value + "&companyId=" + common_company_id;
};